package nl.wubinator.aeve.connectors;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import nl.wubinator.aeve.exceptions.AEveConnectionException;
import nl.wubinator.aeve.url.IEveApiUrl;
import nl.wubinator.aeve.utils.Parameters;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;

abstract class ConnectorBase {

	protected void connect(IEveApiUrl url) throws AEveConnectionException {
		connect(url, null, null);
	}

	/**
	 * The subclass that wants to retrieve information must call this method.
	 * Based on the provided url and parameters it will create a connection to
	 * the Eve API and retrieve the xml
	 * 
	 * @param url
	 * @param parameters
	 * @return
	 */
	protected void connect(IEveApiUrl url, Parameters parameters,
			ContentHandler converter) throws AEveConnectionException {
		try {
			HttpPost httpPost = new HttpPost(url.getUrl());

			if (parameters != null) {
				UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(
						parameters.getParameters(), "ISO-8859-1");

				httpPost.setEntity(p_entity);
			}

			/* Perform the actual HTTP POST */
			DefaultHttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			InputStream inStream = entity.getContent();

			// Retrieve the xml and handle the content
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xr = parser.getXMLReader();
			xr.setContentHandler(converter);
			xr.parse(new InputSource(inStream));
			
			// Check the XML for an error message
		} catch (ClientProtocolException cpeExc) {
			Log.d("Client Protocol Exception", cpeExc.getMessage());
		} catch (SAXException saxExc) {
			Log.d("SAX Exception", saxExc.getMessage());
		} catch (ParserConfigurationException parserExc) {
			Log.d("Parser configuration exception", parserExc.getMessage());
		} catch (IllegalStateException ise) {
			Log.d("Connect exception", ise.getMessage());
		} catch (IOException ioe) {
			Log.d("IO Exception", ioe.getMessage());
		}
	}
}